package licode.unisop.unilite.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 对结果进行拦截统一返回
 *
 * @author licode
 */
@ControllerAdvice
public class UniResponseAdvice implements ResponseBodyAdvice<Object> {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> httpClass) {
        boolean isSupports = false;
        if (null == methodParameter.getMethod()) {
            return false;
        }

        if (methodParameter.getDeclaringClass().isAnnotationPresent(UniIgnoreResult.class) ||
                methodParameter.getMethod().isAnnotationPresent(UniIgnoreResult.class)) {
            return false;
        }

        // 检查注解是否存在，存在则拦截
        isSupports = methodParameter.getDeclaringClass().isAnnotationPresent(UniReturnResult.class) ||
                methodParameter.getMethod().isAnnotationPresent(UniReturnResult.class);
        return isSupports;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof UniResult) {
            return body;
        }
        if (body instanceof String) {
            return objectMapper.writeValueAsString(UniResult.of(body));
        }
        return UniResult.of(body);
    }
}
